package dao

import (
	"fmt"
	"gofar/packed/gerr"
	"gofar/packed/orm"
	"sync"
)

var Table = &tableDao{}

type tableDao struct{}

func (t *tableDao) CreateTable() *gerr.Error {
	sqls := map[string]string{
		"user": `CREATE TABLE IF NOT EXISTS gf_users (
    account varchar(64) NOT NULL COMMENT '用户唯一账号，登录名',
    name varchar(32) NOT NULL COMMENT '用户名，显示名称',
    passwd varchar(255) NOT NULL COMMENT '密码',
    avatar varchar(255) COMMENT '头像',
    email varchar(128) COMMENT '邮箱',
    create_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    update_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (account),
    UNIQUE KEY idx_account (account) USING BTREE,
    KEY idx_passwd (passwd) COMMENT '密码一般索引'
  );`,
		"category": `CREATE TABLE IF NOT EXISTS gf_categorys (
    id int(3) NOT NULL AUTO_INCREMENT COMMENT '分类id',
    name varchar(32) NOT NULL COMMENT '分类名称',
    type int(1) NOT NULL DEFAULT 1 COMMENT '分类类型：1 article，2 post，3 book',
    create_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    update_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (id),
    UNIQUE KEY idx_id (id) USING BTREE,
    KEY idx_type (type) COMMENT '类型'
  );`,
		"article": `CREATE TABLE IF NOT EXISTS gf_articles (
    id int NOT NULL AUTO_INCREMENT COMMENT '文章id',
    title varchar(255) NOT NULL COMMENT '文章标题',
    markdown longtext NOT NULL COMMENT 'Markdown 文本',
    ctg_id int NOT NULL COMMENT '分类id',
    user_id varchar(64) NOT NULL COMMENT '用户id',
    view_count int NOT NULL DEFAULT 0 COMMENT '文章查看数量',
    published int(1) NOT NULL DEFAULT 0 COMMENT '是否发布：0 草稿，1 已发布',
    deleted int(1) NOT NULL DEFAULT 0 COMMENT '软删除：0 未删除，1 已删除',
    create_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    update_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间 同时也是删除日期',
    UNIQUE KEY idx_id (id) USING BTREE,
    KEY idx_ctg_id (ctg_id) COMMENT '分类',
    KEY idx_other (deleted,published) COMMENT '复合索引'
  );`,
	}
	var (
		ws  sync.WaitGroup
		err *gerr.Error
	)
	for key, sql := range sqls {
		ws.Add(1)
		go func(tableName, tableSql string) {
			defer ws.Done()
			db := orm.DB().Exec(tableSql)
			if db.Error != nil && err == nil {
				err = gerr.Swrap(&db.Error, fmt.Sprintf("%s表创建失败：%s", tableName, db.Error.Error()))
			}
		}(key, sql)
	}
	ws.Wait()
	return err
}

func exec(sql *string) error {
	db := orm.DB().Exec(*sql)
	return db.Error
}
